package com.zjitc.backend_shop.controller.Admin;


import com.alibaba.fastjson2.JSON;
import com.zjitc.backend_shop.pojo.Admin;
import com.zjitc.backend_shop.pojo.Category;
import com.zjitc.backend_shop.pojo.Permission;
import com.zjitc.backend_shop.pojo.po.LoginUser;
import com.zjitc.backend_shop.service.AdminService;
import com.zjitc.backend_shop.service.PermissionService;
import com.zjitc.backend_shop.utils.APIResponse;
import com.zjitc.backend_shop.utils.CheckResult;
import com.zjitc.backend_shop.utils.JwtUtils;
import com.zjitc.backend_shop.utils.Token;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.util.StringUtil;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RestController
@Tag(name="角色管理")
@RequestMapping("/admin")
public class AdminController {
    private static final String UPLOAD_OIR = "src/main/resources/static/image/";
    @Autowired
    private AdminService adminService;
    @Autowired
    private PermissionService PermissionService;

    @Operation(summary = "管理员登录")
    @RequestMapping("/login")
    public APIResponse<Token> login(@RequestBody Admin admin) {
        APIResponse apiResponse = new APIResponse();
        String jwt=adminService.login(admin);
        if(!StringUtil.isEmpty(jwt)){
            apiResponse.APIResponseOK(0, "登录成功", new Token(jwt));
        }else{
            apiResponse.APIResponseError(1000, "登录失败！", null);
        }
        return apiResponse;
    }

    @RequestMapping("/text")
    public String text() {
        return "apiResponse";
    }

    @Operation(summary = "修改角色密码")
    @PostMapping("/admin/changePassword")
    public APIResponse<String> changePassword(@RequestBody Admin admin, HttpServletRequest request) {
        APIResponse apiResponse = new APIResponse();

        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);
        admin.setUsername(claims.getSubject());

        if (adminService.changePassword(admin)) {
            apiResponse.APIResponseOK(0, "修改密码成功", null);
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "修改密码失败", null);
            return apiResponse;
        }
    }
    @Operation(summary = "获取当前用户信息")
    @PreAuthorize("hasAuthority('select')")
    @GetMapping("/admin")
    public APIResponse<Admin> findByUsername(HttpServletRequest request){
        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);
        LoginUser loginUser = JSON.parseObject(claims.getSubject(), LoginUser.class);
        Admin admin=adminService.findByUsername(loginUser.getUsername());
        if(!admin.getAvatar().equals("")){
            admin.setAvatar(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/"+admin.getAvatar());
        }
        APIResponse<Admin> apiResponse = new APIResponse<>(0,"",admin);
        return apiResponse;
    }
    @Operation(summary = "上传图片")
    @PostMapping("/upload/picture")
    public APIResponse<String> uploadPicture(@RequestParam("file") MultipartFile file,@RequestParam("type") String type, HttpServletRequest request) {
        APIResponse apiResponse = new APIResponse();
        System.out.println(type);

        // 处理文件上传逻辑
        if (file.isEmpty()) {
            apiResponse.APIResponseError(1001, "文件为空", null);
            return apiResponse;
        }

        try {
            Path uploadPath = Paths.get(UPLOAD_OIR+type);
            if(!Files.exists(uploadPath)){
                Files.createDirectories(uploadPath);
            }
            byte[] bytes = file.getBytes();
            String pathName=UUID.randomUUID()+file.getOriginalFilename();
            Path path=Paths.get(UPLOAD_OIR+type+"/"+pathName);
            Files.write(path,bytes);
            String pathurl=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/image/"+type+"/" + pathName;
            // 保存文件的逻辑
            Map<String,Object> data=new HashMap<>();
            String savepath="static/image/"+type+"/"+pathName;
            data.put("savepath",savepath);
            data.put("url",pathurl);
            data.put("name",pathName);
            apiResponse.APIResponseOK(0, "图片上传成功",data);
            return apiResponse;
        } catch (Exception e) {
            apiResponse.APIResponseError(1002, "图片上传失败", null);
            return apiResponse;
        }
    }
    @Operation(summary = "修改角色头像")
    @PostMapping("/admin/changeAvatar")
    public APIResponse<String> changeAvator(@RequestBody Admin admin, HttpServletRequest request) {
        APIResponse apiResponse = new APIResponse();

        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);
        LoginUser loginUser = JSON.parseObject(claims.getSubject(), LoginUser.class);
        admin.setUsername(loginUser.getUsername());
        System.out.println(admin);
        System.out.println(1);

        if (adminService.changeAvator(admin)) {
            apiResponse.APIResponseOK(0, "修改头像成功", null);
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "修改头像失败", null);
            return apiResponse;
        }
    }
    @Operation(summary = "获取角色权限列表")
    @PreAuthorize("hasAuthority('select')")
    @GetMapping("/user/permission")
    public APIResponse<List<Permission>> findPermissionList(HttpServletRequest request){
        List<Permission> permissions =PermissionService.findAll();
        APIResponse<List<Permission>> apiResponse = new APIResponse<>(0, "", permissions);
        return apiResponse;
    }
    @Operation(summary = "获取角色列表")
    @PreAuthorize("hasAuthority('select')")
    @GetMapping("/role/list")
    public APIResponse<List<Admin>> findUserList(HttpServletRequest request){
        List<Admin> users =adminService.findAllAdmin();
        APIResponse<List<Admin>> apiResponse = new APIResponse<>(0, "", users);
        return apiResponse;
    }
}
